package com.kitty.game.role.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;

import com.alibaba.fastjson.JSONObject;
import com.kitty.common.cache.RedisService;
import com.kitty.common.utils.SpringUtils;
import com.kitty.game.ServerService;
import com.kitty.game.config.Server;
import com.kitty.game.enter.FiedValue;
import com.kitty.game.enter.RespUpdate;
import com.kitty.game.enter.TitleInfo;
import com.kitty.game.equip.message.RespNotifyMiscEx;
import com.kitty.game.equip.service.FabaoService;
import com.kitty.game.pay.PayDataPool;
import com.kitty.game.pay.message.RespPayUrl;
import com.kitty.game.pay.model.PayNotifyInfo;
import com.kitty.game.role.message.ReqGeneralNotify;
import com.kitty.game.role.model.Account;
import com.kitty.game.role.model.Invite;
import com.kitty.game.role.model.Role;
import com.kitty.game.team.message.RespMsg;
import com.kitty.common.model.Reason;
import com.kitty.mina.cache.DataCache;
import com.kitty.mina.message.MessagePusher;
import lombok.extern.slf4j.Slf4j;
import org.apache.mina.core.session.IoSession;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.json.Json;
import org.nutz.json.JsonFormat;
import org.nutz.lang.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;

/*
 *
 * 充值页面   以及接口
 * */
@Service
@Slf4j
public class PayService {
    Logger logger = LoggerFactory.getLogger(PayService.class);

    @Autowired
    ServerService serverService;

    private int rate = 1;//抽奖比例    1比1

    @Autowired
    Dao dao;

    @Autowired
    AccountService accountService;
    @Autowired
    PayService payService;
    @Resource
    FabaoService fabaoService;

    private String notifyUrl;

    private List<Integer> appoints = new ArrayList<>(Arrays.asList(30, 98, 198, 328, 648, 1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000, 10000));

    public void createPayInfo(IoSession session, Role role, ReqGeneralNotify reqGeneralNotify) {
        logger.warn("打开充值页面角色==={}", role.getName());
        Account account = accountService.getAccount(role.getSid());
        if (account == null) {
            return;
        }
        int money = 0;
        switch (reqGeneralNotify.getStatus()) {
            case "6":
                money = 648;
                break;
            case "5":
                money = 328;
                break;
            case "4":
                money = 198;
                break;
            case "3":
                money = 98;
                break;
            case "2":
                money = 30;
                break;
            case "1":
                money = 6;
                break;
        }
        Server server = dao.fetch(Server.class, Cnd.where("sonName", "=", serverService.getServer().getSonName()));
        if (!server.isPayEnable()) {
            return;
        }
//        if (money<98) {
//            MessagePusher.pushMessage(session, new RespMsg("当前选择金额无可用通道，请尝试其他金额。"));
//            return;
//        }
//        String payUrl =getPayUrl(account.getId(), money * 100 +new Random().nextInt(10)+1, role.getUid(), String.valueOf(server.getId()));
        //Account account1 = accountService.getAccount(role.getSid());
        //String payUrl = String.format(server.getPayUrl(), server.getId(), account1, money, role.getUid());
        String payUrl =  DataCache.REDIS_DATA.get("chongzhilianjie");       //String.format(server.getPayUrl(), account.getUsername(), server.getId(), money,account.getChannelCode(),role.getUid());
        logger.warn(payUrl);// 运行起来看一下，這個目前是不是參數穿不過去，找到问题了。你这个链接地址不对

        //
        // http://43.249.193.13/pay/index.php/account=%smoney=%d  getAddress(account.getId(), money);
        if (Strings.isEmpty(payUrl)) {
            MessagePusher.pushMessage(session, new RespMsg("充值系统异常，请稍后再试。"));
            return;
        }
        RespPayUrl respPayUrl = new RespPayUrl();
        respPayUrl.setUrl(payUrl);
        MessagePusher.pushMessage(session, respPayUrl);
    }

    private String crateShortUrl(String longUrl) {
        BufferedReader reader = null;
        try {
            longUrl = URLEncoder.encode(longUrl, "GBK");
            URL url = new URL("http://api.t.sina.com.cn/short_url/shorten.json?source=2849184197&url_long=" + longUrl);
            InputStream iStream = url.openStream();
            reader = new BufferedReader(new InputStreamReader(iStream));
            String jsonStr = reader.readLine();
            JSONObject jsonObj = JSONObject.parseArray(jsonStr).getJSONObject(0);
            return jsonObj.getString("url_short");
        } catch (Exception e) {
            return longUrl;
        } finally {
            IOUtils.closeQuietly(reader);
        }
    }


    /**
     * 处理充值奖励
     */
    public void handleAccumulativeReward(Role role, int money, int addGold) {
        if (role == null) {
            return;
        }
        /**充值活动*/
        // 积分服 元宝只给1避免系统错误
        //chargeActivity(role, money);
        // 抽奖
        //choujiang(role, money * 5);
        //增加元宝
        int bili = Integer.parseInt(SpringUtils.getBean(RedisService.class).get("chongzhi_bili"));
        SpringUtils.getRoleService().addGold(role, money*bili, Reason.PAY);

        int choujiangbili = Integer.parseInt(SpringUtils.getBean(RedisService.class).get("choujiang_bili"));
        payService.choujiang(role, money*choujiangbili);

        int jifenbili = Integer.parseInt(SpringUtils.getBean(RedisService.class).get("jifen_bili"));
        SpringUtils.getRoleService().addRechargeScore(role, money*jifenbili);
        jifen2Leiji(role, money);//算累计
        //自定义活动
        //activity1(role, money);

    }

    /**
     * 2、	每个玩家每天有一次充值30得3倍的机会，充值一次过后变为正常比例（累计充值只记录真实充值）
     * 3、	每个玩家首次单笔充值98、198、328、648、1000、2000、3000、4000、5000得双倍倍元宝和积分；这9项金额充值过一次之后，变为正常比例。（累计充值只记录真实充值）
     */
    private void chargeActivity(Role role, int money) {
        int val = 0;
        if (money == 98) {
            val = money + 18;
        } else if (money == 198) {
            val = money + 38;
        } else if (money == 328) {
            val = money + 68;
        } else if (money == 648) {
            val = money + 188;
        } else if (money == 1000) {
            val = money + 375;
        } else if (money == 2000) {
            val = money + 800;
        } else if (money == 4000) {
            val = money + 1500;
        } else if (money == 5000) {
            val = money + 1875;
        }
        //充值倍数修改
        val = val == 0 ? money : val;
        jifen(role, val * 49);
        SpringUtils.getRoleService().addGold(role, 1, Reason.RECHARGE);
        role.getActivity().getChargeAppoints().add(money);
    }
    public void addReward(int rmb, Role role) {
        logger.error("领取邀请奖励=={}=={}=={}", role.getRoleId(), role.getName(), rmb);
        if (rmb < 5) {
            rmb = 5;
        }
        logger.error("领取邀请奖励=={}=={}=={}", role.getRoleId(), role.getName(), rmb);
        choujiang(role, rmb * rate);
        SpringUtils.getRoleService().addRechargeScore(role, rmb);
    }

    public void choujiang(Role role, int money) {
        /**增加充值积分*/
        Map<String, Integer> welfare = role.getExtendBox().getWelfare();
        welfare.put("lotteryDraw", welfare.getOrDefault("lotteryDraw", 0) + money);
        role.save();
        log.error("choujiang==={}=={}=={}={}", role.getUid(), role.getName(), welfare.getOrDefault("lotteryDraw", 0), money);
        RespUpdate respUpdate = new RespUpdate();
        respUpdate.setRoleId(role.getRoleId());
        respUpdate.setList(new ArrayList<>());
        respUpdate.getList().add(new FiedValue(868, role.getExtendBox().getWelfare().getOrDefault("lotteryDraw", 0)));
//        respUpdate.setList(Collections.singletonList(new FiedValue(868, role.getExtendBox().getWelfare().getOrDefault("lotteryDraw", 0))));
        MessagePusher.pushMessage(role, respUpdate);
        MessagePusher.pushMessage(role, new RespNotifyMiscEx("获得#R" + money + "次#n抽奖"));
    }

    public void jifen(Role role, int money) {
        SpringUtils.getRoleService().addRechargeScore(role, money);
        role.save();
    }

    public void jifen2Leiji(Role role, int money) {
        int oldTotalCharge = role.getTotalCharge();
        role.setTotalCharge(oldTotalCharge + money);
        /**给累计充值称号*/
        ArrayList<Integer> arrayList = new ArrayList(PayDataPool.ACCUMULATIVE_PAY_TITLES.keySet());
        Collections.sort(arrayList);
        for (Integer integer : arrayList) {
            String value = PayDataPool.ACCUMULATIVE_PAY_TITLES.get(integer);
            if (role.getTotalCharge() >= integer) {
                TitleInfo titleInfo = new TitleInfo();
                titleInfo.setType(value);
                titleInfo.setTitle(value);
                SpringUtils.getRoleService().addTitle(role, titleInfo);
            } else {
                SpringUtils.getRoleService().delTitle(role, value);
            }
        }
    }

    public void record(Role role, PayNotifyInfo payNotifyInfo) {
        AccountService accountService = SpringUtils.getBean(AccountService.class);
        Account account = accountService.getAccount(role.getSid());
        if (account == null) {
            return;
        }

        Invite invitAccount = accountService.fetchInvite(account.getUsername());
        if (invitAccount == null) {
            return;
        }
        int size = accountService.countPayGateway(invitAccount.getInviteAccount());
        if (size == 1) {
            Invite invite = new Invite();
            invite.setAccount(account.getUsername());
            invite.setInviteAccount(invitAccount.getInviteAccount());
            invite.setRmb(800);
            invite.setState(0);
            invite.setUpdatetime(new Date());
            invite.setCreatetime(new Date());
            accountService.insertInvite(invite);
        }
        Invite invite = new Invite();
        invite.setAccount(account.getUsername());
        invite.setInviteAccount(invitAccount.getInviteAccount());
        invite.setRmb(payNotifyInfo.getMoney());
        invite.setState(0);
        invite.setUpdatetime(new Date());
        invite.setCreatetime(new Date());
        accountService.insertInvite(invite);
        logger.error("充值添加邀请记录=={}", Json.toJson(invite, JsonFormat.compact()));
    }

    public void title(Role role, String title) {
        TitleInfo titleInfo = new TitleInfo();
        titleInfo.setType(title);
        titleInfo.setTitle(title);
        SpringUtils.getRoleService().addTitle(role, titleInfo);
    }






    public void shoushi(Role role, String content) {
        SpringUtils.getEquipService().getJewelryNew(role, content.substring(0, 4), 1, content, false);
    }
}
